package com.ns.basic.global;

import com.ns.basic.log.utils.ApiLogUtil;
import com.ns.core.annotations.ReqLog;
import com.ns.core.utils.sg.ResultOk;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.Configuration;

/**
 * API全局日志, Controller 层切面
 *
 * @author lw
 */
@Aspect
@Configuration
public class ApiLogAspect {


    /**
     * 定义AOP签名
     */
    @Pointcut("@annotation(com.ns.core.annotations.ReqLog))")
    public void webLogProject() {
    }

    /**
     * 接收请求，并记录数据
     *
     * @param joinPoint joinPoint
     * @param reqLog    reqLog
     */
    @Before(value = "@annotation(reqLog)")
    public void doBefore(JoinPoint joinPoint, ReqLog reqLog) {
        ApiLogUtil.startRequest(joinPoint, reqLog);
    }

    /**
     * 执行成功后处理
     * 可以获取执行时间  响应结果等等
     *
     * @param reqLog reqLog
     * @param ret    响应结果
     */
    @AfterReturning(value = "@annotation(reqLog)", returning = "ret")
    public void doAfterReturning(ReqLog reqLog, Object ret) {
        // 解析返回结果
        if (ret instanceof ResultOk) {
            ApiLogUtil.endRequest((ResultOk) ret);
        } else if (ret instanceof String) {
            ApiLogUtil.endRequest(ResultOk.get(901, String.valueOf(ret)));
        } else {
            ApiLogUtil.endRequest(ResultOk.get(902, String.valueOf(ret)));
        }
    }
}